package org.freedom.imarket.util.converter;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;
import org.springframework.core.convert.converter.Converter;

public class StringToBigDecimal implements Converter<String, BigDecimal> {

	/**
	 * Pattern da utilizzare per la conversione. Default: dd/MM/yyyy
	 */
	private String pattern = "#,##0.00";

	@Override
	public BigDecimal convert(String source) {
		if (source == null) {
			return null;
		}
		if(source.indexOf(",")!=-1){
			String nSource = source.replace(",",".");
			String[] splitted = StringUtils.split(nSource,"."); 
			if(splitted.length>1){
				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < splitted.length; i++) {
					String s = splitted[i];
					if(i==splitted.length-1){
						sb.append(".");
					}
					sb.append(s);
				}
				source=sb.toString(); 
			}else{
				source=nSource;
			}
			
		}
		BigDecimal bd = new BigDecimal(source);
		return bd;
	}

	public static void main(String[] args) throws ParseException {
		String dateToFormat = "30,000,222,14";
		DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale
				.getDefault());
	 	df.applyPattern("#,##0.00");
	}

	public String getPattern() {
		return pattern;
	}

	public void setPattern(String pattern) {
		this.pattern = pattern;
	}
}
